<?php

namespace app\admin\model;

use app\admin\service\Rbac;
use app\common\enums\StatusEnum;
use think\exception\ValidateException;

class Permission extends \app\common\model\Permission
{
    /**
     * 权限列表
     * @param $where
     * @return array
     * @throws \think\exception\DbException
     */
    public static function getList($where)
    {
        $sql = static::field('id, name, category_id, path, description, status, create_time');

        if ($where) {
            $sql->where($where);
        }

        $data = $sql->paginate(null, false, ['query' => request()->param()]);

        $categoryIds = [];
        foreach ($data->items() as $key => $value) {
            $categoryIds[$value['category_id']] = $value['category_id'];
        }

        $cIds = [];
        if ($categoryIds) {
            $category = PermissionCategory::getList([['id', 'in', $categoryIds]]);
            foreach ($category['model'] as $key => $value) {
                $cIds[$value['id']] = $value['name'];
            }
        }

        $model = $data->each(function ($item, $key) use ($cIds) {
            $item['create_time'] = get_datetime($item['create_time']);
            $item['statusText'] = StatusEnum::getStatus($item['status']);
            $item['category_id'] = isset($cIds[$item['category_id']]) ? $cIds[$item['category_id']] : '';
            return $item;
        });

        // 获取总记录数
        $count = $model->total();
        return [
            'model' => $model,
            'count' => $count
        ];
    }

    public static function saveOne($data)
    {
        $rbac = new Rbac();
        return $rbac->createPermission($data);
    }

    public static function deleteOne($ids)
    {
        $rbac = new Rbac();
        return $rbac->delPermission($ids);
    }

    /**
     * 获取权限列表
     * @param $roleId int 角色ID
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getPermissions($roleId = 0)
    {
        $permission = static::field('p.id, p.name, c.id AS categoryId, c.name AS categoryName')
            ->alias('p')
            ->join('permission_category c', 'p.category_id = c.id', 'INNER')
            ->where([
                'p.type' => self::TYPE_BACKEND,
                'p.status' => StatusEnum::ENABLED,
                'c.status' => PermissionCategory::STATUS_ENABLED,
            ])
            ->select()
            ->toArray();

        $rolePermission = [];
        if ($roleId > 0) {
            $rolePermission = RolePermission::getColumn($roleId);
        }

        $result = [];
        $noActive = [];
        foreach ($permission as $key => $value) {
            $value['active'] = isset($rolePermission[$value['id']]) ? true : false;

            if ($value['active'] === false) {
                $noActive[$value['id']] = $value['active'];
            }

            $result[$value['categoryId']]['categoryId'] = $value['categoryId'];
            $result[$value['categoryId']]['categoryName'] = $value['categoryName'];
            $result[$value['categoryId']]['permission'][] = $value;
        }

        foreach ($result as $key => $value) {
            $result[$key]['permission'] = array_chunk($value['permission'], 4, true);
            // 初始化未全部选中
            $result[$key]['active'] = true;
        }

        if ($noActive) {
            // 未选中的权限查找对应的目录
            $category = self::getCategory(array_keys($noActive));
            $category = array_flip($category);
            foreach ($result as $key => $value) {
                // 给对应的目录状态改完未全选
                $result[$key]['active'] = isset($category[$value['categoryId']]) ? false : true;
            }
        }

        return $result;
    }

    /**
     * 根据权限ID获取目录
     * @param $ids
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getCategory($ids)
    {
        return static::field('id, category_id')->where('id', 'in', $ids)->select()->column('category_id', 'id');
    }
}